﻿using Absky.Cache.Factory;
using Absky.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace Absky.Web.Operator
{
    public class Operator
    {
        public static Operator Instance
        {
            get { return new Operator(); }
        }

        private readonly string LoginProvider = GlobalContext.Configuration.GetSection("SystemConfig:LoginProvider").Value;
        private readonly string TokenName = "UserToken"; //cookie name or session name

        public async Task AddCurrent(string token)
        {
            switch (LoginProvider)
            {
                case "Cookie":
                    CookieHelper.WriteCookie(TokenName, token);
                    break;

                case "Session":
                    SessionHelper.WriteSession(TokenName, token);
                    break;

                case "WebApi":
                    OperatorInfo user = await new DataRepository().GetUserByToken(token);
                    if (user != null)
                    {
                        CacheFactory.Cache.SetCache(token, user);
                    }
                    break;

                default:
                    throw new Exception("未找到LoginProvider配置");
            }
        }

        /// <summary>
        /// Api接口需要传入apiToken
        /// </summary>
        /// <param name="apiToken"></param>
        public void RemoveCurrent(string apiToken = "")
        {
            switch (LoginProvider)
            {
                case "Cookie":
                    CookieHelper.RemoveCookie(TokenName);
                    break;

                case "Session":
                    SessionHelper.RemoveSession(TokenName);
                    break;

                case "WebApi":
                    CacheFactory.Cache.RemoveCache(apiToken);
                    break;

                default:
                    throw new Exception("未找到LoginProvider配置");
            }
        }

        /// <summary>
        /// Api接口需要传入apiToken
        /// </summary>
        /// <param name="apiToken"></param>
        /// <returns></returns>
        public async Task<OperatorInfo> Current(string apiToken = "")
        {
            IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
            OperatorInfo user = null;
            string token = string.Empty;
            switch (LoginProvider)
            {
                case "Cookie":
                    if (hca.HttpContext != null)
                    {
                        token = CookieHelper.GetCookie(TokenName);
                    }
                    break;

                case "Session":
                    if (hca.HttpContext != null)
                    {
                        token = SessionHelper.GetSession(TokenName);
                    }
                    break;

                case "WebApi":
                    token = apiToken;
                    break;
            }
            if (string.IsNullOrEmpty(token))
            {
                return user;
            }
            token = token.Trim('"');
            user = CacheFactory.Cache.GetCache<OperatorInfo>(token);
            if (user == null)
            {
                user = await new DataRepository().GetUserByToken(token);
                if (user != null)
                {
                    CacheFactory.Cache.SetCache(token, user);
                }
            }
            return user;
        }
        #region 登录错误次数记录
        /// <summary>
        /// 获取当前登录错误次数
        /// </summary>
        /// <returns></returns>
        public async Task<int> GetCurrentErrorNum()
        {
            int res = 0;
            IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
            string token;
            switch (LoginProvider)
            {
                case "Cookie":
                    if (hca.HttpContext != null)
                    {
                        token = CookieHelper.GetCookie(TokenName);
                        if (string.IsNullOrEmpty(token))
                        {
                            token = Guid.NewGuid().ToString();
                            CookieHelper.WriteCookie(TokenName, token);
                        }
                        string num = CacheFactory.Cache.GetCache<string>("error:" + token);
                        if (!string.IsNullOrEmpty(num))
                        {
                            res = Convert.ToInt32(num);
                        }
                        return await Task.FromResult(res);
                    }
                    break;

                case "Session":
                    if (hca.HttpContext != null)
                    {
                        token = SessionHelper.GetSession(TokenName);
                        if (string.IsNullOrEmpty(token))
                        {
                            token = Guid.NewGuid().ToString();
                            SessionHelper.WriteSession(TokenName, token);
                        }
                        string num = CacheFactory.Cache.GetCache<string>("error:" + token);
                        if (!string.IsNullOrEmpty(num))
                        {
                            res = Convert.ToInt32(num);
                        }
                        return await Task.FromResult(res);
                    }
                    break;

                //case "WebApi":
                //    token = apiToken;
                //    break;
            }
            return 0;
        }
        /// <summary>
        /// 增加错误次数
        /// </summary>
        /// <returns></returns>
        public async Task<int> AddCurrentErrorNum()
        {
            int res = 0;
            IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
            string token;
            switch (LoginProvider)
            {
                case "Cookie":
                    if (hca.HttpContext != null)
                    {
                        token = CookieHelper.GetCookie(TokenName);
                        if (string.IsNullOrEmpty(token))
                        {
                            token = Guid.NewGuid().ToString();
                            CookieHelper.WriteCookie(TokenName, token);
                        }
                        string num = CacheFactory.Cache.GetCache<string>("error:" + token);
                        if (!string.IsNullOrEmpty(num))
                        {
                            res = Convert.ToInt32(num);
                        }
                        res++;
                        num = res + "";
                        CacheFactory.Cache.SetCache<string>("error:" + token, num);
                    }
                    break;

                case "Session":
                    if (hca.HttpContext != null)
                    {
                        token = SessionHelper.GetSession(TokenName);
                        if (string.IsNullOrEmpty(token))
                        {
                            token = Guid.NewGuid().ToString();
                            SessionHelper.WriteSession(TokenName, token);
                        }
                        string num = CacheFactory.Cache.GetCache<string>("error:" + token);
                        if (!string.IsNullOrEmpty(num))
                        {
                            res = Convert.ToInt32(num);
                        }
                        res++;
                        num = res + "";
                        CacheFactory.Cache.SetCache<string>("error:" + token, num);
                    }
                    break;
            }
            return await Task.FromResult(res);
        }
        /// <summary>
        /// 清除当前登录错误次数
        /// </summary>
        public void ClearCurrentErrorNum()
        {
            IHttpContextAccessor hca = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>();
            string token;
            switch (LoginProvider)
            {
                case "Cookie":
                    if (hca.HttpContext != null)
                    {
                        token = CookieHelper.GetCookie(TokenName);
                        if (string.IsNullOrEmpty(token))
                        {
                            token = Guid.NewGuid().ToString();
                            CookieHelper.WriteCookie(TokenName, token);
                        }
                        CacheFactory.Cache.RemoveCache("error:" + token);
                    }
                    break;

                case "Session":
                    if (hca.HttpContext != null)
                    {
                        token = SessionHelper.GetSession(TokenName);
                        if (string.IsNullOrEmpty(token))
                        {
                            token = Guid.NewGuid().ToString();
                            SessionHelper.WriteSession(TokenName, token);
                        }
                        CacheFactory.Cache.RemoveCache("error:" + token);
                    }
                    break;
            }
        }
        #endregion
    }
}
